﻿using Customer.API.Applcation.Command.SalesCommand;
using Customer.Domain;
using Customer.Infrstructre;
using Customer.Infrstructre.SalesManager;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Customer.API.Applcation.CommandHandlers.SalesCommandHandler
{
    public class SalesUpdCommandHandler : IRequestHandler<SalesUpdCommand, int>
    {

        ISalesRepository sRep;
        ISellProductRepository spRep;
        EFCoreDBcontext dbContext;

        public SalesUpdCommandHandler(ISalesRepository sRep, EFCoreDBcontext dbContext, ISellProductRepository spRep)
        {
            this.sRep = sRep;
            this.dbContext = dbContext;
            this.spRep = spRep;
        }

        public async Task<int> Handle(SalesUpdCommand request, CancellationToken cancellationToken)
        {
            using (var tran = await dbContext.Database.BeginTransactionAsync((System.Data.IsolationLevel.Serializable)))
            {

                try
                {
                    var se = (await sRep.GetAsync(x => x.SalesId == request.AddDto.SalesId)).FirstOrDefault();

                    se.SalesId = request.AddDto.SalesId;
                    se.SalesCode = request.AddDto.SalesCode;
                    se.DocumentType = request.AddDto.DocumentType;
                    se.MorderNumber = request.AddDto.MorderNumber;
                    se.ClientCode = request.AddDto.ClientCode;
                    se.ClientName = request.AddDto.ClientName;
                    se.SalesName = request.AddDto.SalesName;
                    se.SalesPhone = request.AddDto.SalesPhone;
                    se.ShipmentsTime = request.AddDto.ShipmentsTime;
                    se.Sremark = request.AddDto.Sremark;
                    se.MakePerson = request.AddDto.MakePerson;
                    se.SalesTime = request.AddDto.SalesTime;
                    se.Office_Id = request.AddDto.Office_Id;
                    se.User_Id = request.AddDto.User_Id;
                   
                    var taskToAdd = await sRep.Update(se);

                    foreach (var item in request.AddDto.addSales)
                    {
                        var list = (await spRep.GetAsync(c => c.SalesCode == se.SalesCode)).FirstOrDefault();

                        list.SalesCode = se.SalesCode;
                        list.ProductsId = item.ProductsId;
                        list.SellProductNum = item.SellProductNum;
                        list.Office_Id = request.AddDto.Office_Id;
                        list.User_Id = request.AddDto.User_Id;
                        await spRep.Update(list);
                    }

                    // 提交事务
                    await tran.CommitAsync();

                    return 1;  // 返回最终的结果
                }
                catch (Exception)
                {
                    // 回滚事务
                    await tran.RollbackAsync();
                    throw;
                }
            }
        }
    }
}
